package com.example.maggie.meizinote.mvp.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.tu.loadingdialog.LoadingDailog;
import com.example.maggie.meizinote.app.MApp;
import com.example.maggie.meizinote.app.bean.note_item;
import com.example.maggie.meizinote.app.utils.richeditor.RichEditor;
import com.example.maggie.meizinote.mvp.listener.AddUrlListener;
import com.example.maggie.meizinote.mvp.listener.EditJavaScriptInterface;
import com.example.maggie.meizinote.mvp.ui.adapter.ColorSelectAdapter;
import com.example.maggie.meizinote.mvp.ui.widget.AddUrlDialog;
import com.example.maggie.meizinote.mvp.ui.widget.YesOrNoDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.example.maggie.meizinote.di.component.DaggerNoteEditComponent;
import com.example.maggie.meizinote.di.module.NoteEditModule;
import com.example.maggie.meizinote.mvp.contract.NoteEditContract;
import com.example.maggie.meizinote.mvp.presenter.NoteEditPresenter;

import com.example.maggie.meizinote.R;
import com.lqr.picselect.LQRPhotoSelectUtils;


import java.io.File;
import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class NoteEditActivity extends BaseActivity<NoteEditPresenter> implements NoteEditContract.View {
    @BindView(R.id.editor)
    RichEditor editor;
    @BindView(R.id.preview)
    TextView preview;
    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout)
    LinearLayout layout;
    @BindView(R.id.colors)
    RecyclerView colorsRecyclerView;
    LQRPhotoSelectUtils mLqrPhotoSelectUtils;
    LoadingDailog dialog;

    @Inject
    ColorSelectAdapter adapter;

    private ArrayList<Integer> txtColors = new ArrayList<>();

    private ArrayList<Integer> bgColors = new ArrayList<>();

    private void initColorList() {
        txtColors.add(Color.BLACK);
        txtColors.add(Color.BLUE);
        txtColors.add(Color.CYAN);
        txtColors.add(Color.DKGRAY);
        txtColors.add(Color.GRAY);
        txtColors.add(Color.GREEN);
        txtColors.add(Color.LTGRAY);
        txtColors.add(Color.MAGENTA);
        txtColors.add(Color.RED);
        txtColors.add(Color.YELLOW);


        bgColors.add(Color.WHITE);
        bgColors.add(Color.TRANSPARENT);
        bgColors.add(Color.BLACK);
        bgColors.add(Color.BLUE);
        bgColors.add(Color.CYAN);
        bgColors.add(Color.DKGRAY);
        bgColors.add(Color.GRAY);
        bgColors.add(Color.GREEN);
        bgColors.add(Color.LTGRAY);
        bgColors.add(Color.MAGENTA);
        bgColors.add(Color.RED);
        bgColors.add(Color.YELLOW);
    }

    @Override
    public void showColorDialog(String tilte, int type) {
        colorsRecyclerView.setVisibility(View.VISIBLE);
        adapter.setNewData(type == 0 ? txtColors : type == 1 ? bgColors : new ArrayList<>());
    }

    @OnClick({R.id.action_undo, R.id.action_redo
            , R.id.action_bold, R.id.action_italic
            , R.id.action_subscript, R.id.action_superscript
            , R.id.action_strikethrough, R.id.action_underline
            , R.id.action_heading1, R.id.action_heading2
            , R.id.action_heading3, R.id.action_heading4
            , R.id.action_heading5, R.id.action_heading6
            , R.id.action_txt_color, R.id.action_bg_color
            , R.id.action_indent, R.id.action_outdent
            , R.id.action_align_left, R.id.action_align_center
            , R.id.action_align_right, R.id.action_blockquote
            , R.id.action_insert_bullets, R.id.action_insert_numbers
            , R.id.action_insert_image, R.id.action_insert_link
            , R.id.action_insert_checkbox, R.id.delete, R.id.look
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.action_undo:
                editor.undo();
                break;
            case R.id.action_redo:
                editor.redo();
                break;
            case R.id.action_bold:
                editor.setBold();
                break;
            case R.id.action_italic:
                editor.setItalic();
                break;
            case R.id.action_subscript:
                editor.setSubscript();
                break;
            case R.id.action_superscript:
                editor.setSuperscript();
                break;
            case R.id.action_strikethrough:
                editor.setStrikeThrough();
                break;
            case R.id.action_underline:
                editor.setUnderline();
                break;
            case R.id.action_heading1:
                editor.setHeading(1);
                break;
            case R.id.action_heading2:
                editor.setHeading(2);
                break;
            case R.id.action_heading3:
                editor.setHeading(3);
                break;
            case R.id.action_heading4:
                editor.setHeading(4);
                break;
            case R.id.action_heading5:
                editor.setHeading(5);
                break;
            case R.id.action_heading6:
                editor.setHeading(6);
                break;
            case R.id.action_txt_color:
                //选择颜色
                mPresenter.selectColor(0);
                break;
            case R.id.action_bg_color:
                //选择颜色
                mPresenter.selectColor(1);
                break;
            case R.id.action_indent:
                editor.setIndent();
                break;
            case R.id.action_outdent:
                editor.setOutdent();
                break;
            case R.id.action_align_left:
                editor.setAlignLeft();
                break;
            case R.id.action_align_center:
                editor.setAlignCenter();
                break;
            case R.id.action_align_right:
                editor.setAlignRight();
                break;
            case R.id.action_blockquote:
                editor.setBlockquote();
                break;
            case R.id.action_insert_bullets:
                editor.setBullets();
                break;
            case R.id.action_insert_numbers:
                editor.setNumbers();
                break;
            case R.id.action_insert_image:
                //选择图片
                mLqrPhotoSelectUtils.selectPhoto();
                break;
            case R.id.action_insert_link:
                new AddUrlDialog.Builder(this)
                        .setTitle("添加超链接")
                        .setNegativeButton("确定", mPresenter)
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).create().show();
                break;
            case R.id.action_insert_checkbox:
                editor.insertTodo();
                break;
            case R.id.look:
                //预览
                launchActivity(new Intent(this, NoteTTSActivity.class)
                        .putExtra("content", editor.getHtml()));
                break;
            case R.id.delete:
                new YesOrNoDialog.Builder(this)
                        .setTitle("删除")
                        .setMessage("是否删除当前笔记？")
                        .setNegativeButton("再想想", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mPresenter.delect();
                                dialogInterface.dismiss();
                            }
                        }).create().show();
                break;
        }
    }

    public void dayOrNight() {
        if (MApp.isNight) {
            title.setTextColor(getResources().getColor(R.color.white));
            layout.setBackgroundColor(getResources().getColor(R.color.night_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.night_toolbar_color));

            editor.setBackgroundColor(getResources().getColor(R.color.night_bg_color)); // 设置背景色
            editor.getBackground().setAlpha(0); // 设置填充透明度 范围：0-255
        } else {
            title.setTextColor(getResources().getColor(R.color.black));
            layout.setBackgroundColor(getResources().getColor(R.color.day_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            editor.getBackground().setAlpha(255); // 设置填充透明度 范围：0-255
        }
        setColor();
    }

    public void setColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (MApp.isNight)
                window.setStatusBarColor(getResources().getColor(R.color.night_toolbar_color));
            else
                window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
    }


    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerNoteEditComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .noteEditModule(new NoteEditModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        attachToActivityForResult(requestCode, resultCode, data);
    }

    private void attachToActivityForResult(int requestCode, int resultCode, Intent data) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，申请权限。

        } else {
            // 在Activity中的onActivityResult()方法里与LQRPhotoSelectUtils关联
            mLqrPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_note_edit; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setTitle("笔记");
        initColorList();
        note_item note_item = (note_item) getIntent().getSerializableExtra("note");
        mPresenter.setClassifyId(getIntent().getStringExtra("classifyId"));
        initView();
        if (note_item != null) {
            setNowData(note_item);
            mPresenter.setId(note_item.getObjectId());
            mPresenter.setClassifyId(note_item.getClassify_id());
        } else mPresenter.createNote();
    }

    @Override
    public void setNowData(note_item note) {
        title.setText(note.getNote_title());
        editor.setHtml(note.getContent());
    }

    @Override
    public void setUrl(String title, String url) {
        editor.insertLink(url, title);
    }

    @Override
    public void setImg(String title, String url) {
        editor.insertImage(url, title);
    }

    @Override
    public void setTextColor(int color) {
        editor.setTextColor(color);
        colorsRecyclerView.setVisibility(View.GONE);
    }

    @Override
    public void setTextBackgroundColor(int color) {
        editor.setTextBackgroundColor(color);
        colorsRecyclerView.setVisibility(View.GONE);
    }

    private void initView() {
        LinearLayoutManager ms = new LinearLayoutManager(this);
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置 recyclerview 布局方式为横向布局
        colorsRecyclerView.setLayoutManager(ms);  //给RecyClerView 添加设置好的布局样式
        colorsRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(mPresenter);

        //这个是给图片设置点击监听的，如果你项目需要webview中图片，点击查看大图功能，可以这么添加
        editor.addJavascriptInterface(new EditJavaScriptInterface(this), "imagelistner");
        dialog = new LoadingDailog.Builder(this)
                .setMessage("图片上传中...")
                .setCancelable(true)
                .setCancelOutside(true).create();
        mLqrPhotoSelectUtils = new LQRPhotoSelectUtils(this, new LQRPhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri) {
                //上传图片并添加
                mPresenter.updataImg(outputFile);
            }
        }, true);
//        editor.setEditorHeight(200);
//        editor.setEditorFontSize(22);
//        editor.setEditorFontColor(Color.RED);
        //mEditor.setEditorBackgroundColor(Color.BLUE);
//        mEditor.setBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundResource(R.drawable.bg);
        editor.setPadding(10, 10, 10, 10);
        //mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
        editor.setPlaceholder("Insert text here...");
        //mEditor.setInputEnabled(false);
        editor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
                preview.setText(text);
            }
        });
        dayOrNight();
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        mPresenter.updataNote(title.getText().toString(), editor.getHtml());
        super.onDestroy();
    }

    @Override
    public void killMyself() {
        finish();
    }


}
